<!DOCTYPE html><html lang="zh-CN"><head>
    <meta charset="UTF-8">
    <title>聊天</title>
    <meta name="viewport" content=" initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta name="apple-mobile-web-app-capable" content="no">
    <!--<link href="http://3gimg.qq.com/tmt/dist/proj-dkf-h5/css/dkf-h5.css?t=2014042201" rel="stylesheet" />-->
    <link href="http://3glogo.gtimg.com/wxEnterprise/static/style/dkf-h5/css/dkf-h5.css?t=20140827" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="http://wximg.gtimg.com/tmt/proj-dkf-h5/dist/css/style-voice-sending.css">
    <style>
html,body{height:100%}body{overflow:hidden;background-color:#fff}.mod-chat__separate{margin-bottom:0}.mod-chat__item{margin-bottom:15px}.mod-chat__message{padding:10px 15px;line-height:15px}.nick{font-size:12px;color:#989DA5}.bar-right{right:0;width:50%;display:block;position:fixed;top:0;height:41px;background-color:#fbfcfc;opacity:.95;filter:alpha(opacity=95);-webkit-box-shadow:0 1px 3px rgba(0,0,0,.2);-moz-box-shadow:0 1px 3px rgba(0,0,0,.2);box-shadow:0 1px 3px rgba(0,0,0,.2);z-index:10}.icon_go-close{background-image:url(http://o2o.gtimg.com/dkf/img/wx/close.png?t=123);width:18px;height:18px;margin-top:12px}.fright{float:right}.mright{margin-right:10px}.ui-refresh{overflow-x:hidden !important}.icoVoice{display:inline-block;float:right;width:25px;height:20px;background:url("https://res.wx.qq.com/zh_CN/htmledition/images/icon_sound17ced3.png") no-repeat 0 -1px;cursor:pointer}.icoVoicePlaying {display: inline-block;float: right;width: 25px;height: 20px;background: url("http://o2o.gtimg.com/dkf/img/wx/voiceplayinggreen.gif") no-repeat left 0px;}.mod-chat__message_map{padding:0}.mod-chat__message_map .mod-chat__message-img{width:120px;height:120px}.mod-chat__message-img{height:120px}.mod-topbar_warn .mod-topbar__inner{position:fixed}.mod-pop__inner{position:fixed}
    </style>
    <link rel="stylesheet" type="text/css" href="http://o2o.gtimg.com/dkf/img/wx/refresh.css?t=20140429">
</head>
<body>
<!--顶部导航条-->
<div class="mod-topbar mod-topbar_warn" style="display:none" id="newswarn_btn">
<div class="mod-topbar__inner">
        <div class="mod-topbar__back"><i class="mod-topbar__back-icon icon mod-tapbar__icon_message"></i></div>
        <div class="mod-topbar__title">新消息提醒</div>
    </div>
</div>
<!--消息对话条目列表-->
<div class="ui-refresh" id="ui-refresh">
<div class="ui-refresh-up"><span class="ui-refresh-icon"></span><span class="ui-refresh-label">点击加载更多</span></div> <!--setup方式带有class为ui-refresh-down或ui-refresh-up的元素必须加上，用于放refresh按钮--> 
<div class="mod-chat" id="chat_chatmsglist"><div class="mod-chat__separate"><span class="ui-c-light mod-chat__separate-text">12-26</span></div><div class="mod-chat__item" un="item_{#id#}"><div class="mod-chat__message">1 </div></div><div class="mod-chat__item" un="item_{#id#}"><div class="mod-chat__message">1 </div></div><div class="mod-chat__item" un="item_{#id#}"><div class="mod-chat__message">去 </div></div><div class="mod-chat__separate"><span class="ui-c-light mod-chat__separate-text">上午 00:48</span></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> 你好 </div></div><div class="mod-chat__separate"><span class="ui-c-light mod-chat__separate-text">上午 01:35</span></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <img src="http://o2o.gtimg.com/dkf/img/wx/13.png"><img src="http://o2o.gtimg.com/dkf/img/wx/7.png"><img src="http://o2o.gtimg.com/dkf/img/wx/0.png"> </div></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <span class="icoVoice play" un="voiceStatus" onclick="play('http://crm2.dkf.qq.com/cgi-bin/crmwxmedia/downloadmedia4wechat?bossuin=4100380519&amp;vt=1&amp;mediaid=W5rEsq7G8FJhqHlX7eLIrm9-hE5KPm2EznVpUgTl7-HosUZFv7Ocl0quX2dXy3HV&amp;timestamp=1451583362&amp;appid=wxfe20f87cdf852ee3',this)"></span> </div></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <span class="icoVoice play" un="voiceStatus" onclick="play('http://crm2.dkf.qq.com/cgi-bin/crmwxmedia/downloadmedia4wechat?bossuin=4100380519&amp;vt=1&amp;mediaid=WAzBEzk7FVgFsKY6ZULELmeNJTc8j5cKNAnITFdSY7BbnxeRTu7KRhJyJYCkwsZo&amp;timestamp=1451583364&amp;appid=wxfe20f87cdf852ee3',this)"></span> </div></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <span class="icoVoice play" un="voiceStatus" onclick="play('http://crm2.dkf.qq.com/cgi-bin/crmwxmedia/downloadmedia4wechat?bossuin=4100380519&amp;vt=1&amp;mediaid=s_M1K57Oux-NXRni1dhASLlw5Em4YZZFmFvXqZzQTvFSg324nEqEcJ9Fso8uSb77&amp;timestamp=1451583401&amp;appid=wxfe20f87cdf852ee3',this)"></span> </div></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <img src="http://o2o.gtimg.com/dkf/img/wx/11.png"> </div></div><div class="mod-chat__separate"><span class="ui-c-light mod-chat__separate-text">上午 01:55</span></div><div class="mod-chat__item mod-chat__item_mine" un="item_{#id#}"><div class="nick">小优</div><div class="mod-chat__message"> <img src="http://o2o.gtimg.com/dkf/img/wx/8.png"> </div></div>
</div>
</div>
<!--页脚-->
<!--输入框-->
<!--
    .mod-input_unfolder 用来切换展开和收起
-->
<!--<div class="mod-input mod-input_unfolder">-->
<div class="mod-input" id="input_con">
    <div class="mod-input__inner">
        <div class="mod-input__bar">
        <div id="caseexist">
        <div class="mod-input__op">
            <a class="mod-input__op-item"><i class="icon icon_chat-emoji" id="iconemojibtn"></i></a>
                    <a class="mod-input__op-item"><i class="icon icon_chat-more" id="iconmorebtn"></i></a>
        </div>
        <div class="mod-input__submit ui-fl-r ui-pl-medium"><a href="javascript:;" class="button button_green button_round" id="sendmBtn">发送</a></div>
        <div class="mod-input__inputbox">
           <input type="" class="input_text input_fluid" id="textInput">
           <a class="voice-sending" style="display:none;" id="recordbtn">按住录音</a>
        </div>
        </div>
         <div class="ui-gap" style="padding-bottom:0;display:none" id="casenotexist">
            <a class="button button_round button_green button_block" href="javascript:;" onclick="grabCustomer(1)">发起会话</a>
        </div>
        </div>

   		<div class="mod-input__extend" id="emojicon" style="display: none;">
            <div class="mod-slider">
                <div class="mod-slider__wrap">
                    <!--请写入宽度值-->
                   <div class="mod-slider__list" style="width:1500px;">

                       <!--请写入宽度值-->
                       <div class="mod-slider__item" style="width:320px;">
                           <div class="mod-emoji">
                               <table class="mod-emoji__table" id="">
                                   <tbody><tr>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/0@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/1@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/2@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/3@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/4@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/5@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/6@2x.png" alt=""></td>
                                   </tr>
                                   <tr>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/7@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/8@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/9@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/10@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/11@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/12@2x.png" alt=""></td>
                                       <td><img src="http://o2o.gtimg.com/dkf/img/wx/13@2x.png" alt=""></td>
                                   </tr>
                               </tbody></table>
                           </div>
                       </div>
                   </div>
                </div>
    </div>
</div>
	</div>
</div>
<div class="mod-pop mod-pop_mini" id="tipsCon" style="display:none">
<div class="mod-pop__inner">
<div class="mod-pop__body">
<div class="mod-pop__tips ui-fz-large ui-ta-c" id="tipsmsg"></div>
</div>
<div class="mod-pop__foot">
<a class="button button_dark button_block" onclick="grabCustomer(0);" href="javascript:;" style="float: left;width:35%;margin-bottom:8px">确定</a>
<a class="button button_dark button_block" onclick="$('#tipsCon').hide();" href="javascript:;" style="float: right;width:35%
">取消</a></div>
</div></div>
<audio id="audio1" style="display:none">
</audio>
<div class="voice-sending__layer" style="display:none" id="tipvoice">
    录音中<i class="voice-sending__dot voice-sending__dot_1"></i><i class="voice-sending__dot voice-sending__dot_2"></i><i class="voice-sending__dot voice-sending__dot_3"></i>
</div>
<div class="ui-mask" id="floatBgCon" style="display:none"></div>
<div class="mod-more-list" id="moreCon" style="display:none">
    <div class="mod-more-list__block">
        <div class="mod-more-list__item" id="switchbtn">客服转接</div>
    </div>
    <div class="mod-more-list__block" style="display:none" id="imagebtn">
        <div class="mod-more-list__item">图片</div>
    </div>
    <div class="mod-more-list__block" style="display:none" id="voicebtn">
        <div class="mod-more-list__item">语音</div>
    </div>
    <div class="mod-more-list__block">
        <div class="mod-more-list__item mod-more-list__item_danger" id="cancelmorebtn">取消</div>
    </div>
</div>



<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>

var _retCoderdel=null;
var _retCodergrab=null;
var _retCodergeturl=null;
var _retCoderunread=null;
var _retCoderpushurl=null;

var GlobalConfig = {
	geturl : "?",
	getunreadurl:"?",
	pushurl : "?",
	grabcustomer:"?",
	f: "",
	title: "",
	cid:"",
	uin:"",
	openid:"",
	w:"",
	day:1,//拉取历史聊天记录的天数，默认为1天内
	mid:0,//正在发送的midid
	his:1,//是否是历史聊天记录
	test:"",
    lasttime:"",
	pid:0,//获取消息页数
	flag:0,//标明是否拉取历史消息，0为向下模式 1为向上模式
	unread:0,//标明是否拉取的是未读消息， 0为未读消息  1为历史消息
	isrecording:0,//是否正在录音
	chathtml:"",
	chatmehtml:'<div class="mod-chat__item mod-chat__item_mine"  un="item_{#id#}"><div class="nick">{#nick#}</div><div class="mod-chat__message"> {#ccon#} </div></div>',
	chatyouhtml:'<div class="mod-chat__item" un="item_{#id#}"><div class="mod-chat__message">{#ccon#} </div></div>',
	chataudiohtml:'<div class="mod-chat__message mod-chat__message_audio" style="width:20%;"><i class="icon icon_mod-chat-audio"></i></div>',
	chattime:'<div class="mod-chat__separate"><span class="ui-c-light mod-chat__separate-text">{#msgtime#}</span></div>',
	chattmphtml:'<div class="mod-chat__item  mod-chat__item_mine mod-chat__item_tmp" id="chattmphtml"><div class="nick">{#nick#}</div><div class="mod-chat__message mod-chat__message_audio"><i class="icon icon_mod-chat-audio"></i></div></div>'
};


function $loadUrl(o) {
    o.element = o.element || 'script';
	var el = document.createElement(o.element);
	el.charset = o.charset || 'utf-8';
	o.onBeforeSend&&o.onBeforeSend(el);//发请求之前调用的函数
	el.onload = el.onreadystatechange = function() {
		if(/loaded|complete/i.test(this.readyState) || navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
	            o.onLoad&&o.onLoad();//
                    clear();
		}
	};
	el.onerror = function(){
		clear();
	};
	el.src = o.url;
	document.getElementsByTagName('head')[0].appendChild(el);
	
	function clear(){
		if(!el){return ;}
		el.onload = el.onreadystatechange = el.onerror = null;
		el.parentNode&&(el.parentNode.removeChild(el));
		el = null;
	}
}
window.browser={
	versions:function(){
		var u = navigator.userAgent, app = navigator.appVersion;
		return {
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
		};
	}()
}
//当前脚本版本号
var script_server_version_list = ['1.4','1.10'];
//待请求脚本队列
var script_list = ['http://dkf.qq.com/wkf/js/zepto.min.js', 'http://dkf.qq.com/wkf/js/wxcommon.js'];
if(!browser.versions.ios){
script_list = ['http://dkf.qq.com/wkf/js/zepto.min.js', 'http://dkf.qq.com/wkf/js/wxcommonforad.js'];
}
//脚本LS名称
var script_name_list = ['zepto', 'wxcommon'];


(function () {
	//异步获取文件
	function ajaxGet(url, callback) {
		var request = new XMLHttpRequest();
		if (!request) { return; }
		request.open("GET", url, true);
		request.onreadystatechange = function () {
			if (request.readyState == 4) {
				callback(request.responseText);
			}
		};
		request.send(null);
	}
	
	//本地版本号
	var zepto_version_local = localStorage['zepto_version'] ;
	var wxcommon_version_local = localStorage['wxcommon_version'] ;
	//如果版本号不一致，或者不存在缓存
	if(zepto_version_local!=script_server_version_list[0]){
		ajaxGet(script_list[0] + '?v=' + script_server_version_list[0], function (data) {
		    //存入缓存
			if(data == "" || data == undefined)
			{
				localStorage.removeItem('zepto_version');
				localStorage.removeItem(script_name_list[0]);
				$loadUrl({url: script_list[0] + '?v=' + script_server_version_list[0]});
			}
			else
			{
				localStorage[script_name_list[0]] = data;
			    localStorage['zepto_version']=script_server_version_list[0];
			    eval(data);
			}
			
			//如果版本号不一致，或者不存在缓存
			if(wxcommon_version_local!=script_server_version_list[1]){
				ajaxGet(script_list[1] + '?v=' + script_server_version_list[1], function (data) {
					if(data == "" || data == undefined)
					{
						localStorage.removeItem('wxcommon_version');
						localStorage.removeItem(script_name_list[1]);
						$loadUrl({url: script_list[1] + '?v=' + script_server_version_list[1]});
					}
					else
					{
						localStorage[script_name_list[1]] = data;
						localStorage['wxcommon_version']=script_server_version_list[1];
						eval(data);
					}
					getparams();
				});
			}
			else{
				eval(localStorage['wxcommon']);
				getparams();
			}
		});
	}
	else if(wxcommon_version_local!=script_server_version_list[1]){
		eval(localStorage['zepto']);
		ajaxGet(script_list[1] + '?v=' + script_server_version_list[1], function (data) {
			if(data == "" || data == undefined)
			{
				localStorage.removeItem('wxcommon_version');
				localStorage.removeItem(script_name_list[1]);
				$loadUrl({url: script_list[1] + '?v=' + script_server_version_list[1]});
			}
			else
			{
				localStorage[script_name_list[1]] = data;
				localStorage['wxcommon_version']=script_server_version_list[1];
				eval(data);
			}
			getparams();
		});
	}
	else{
		eval(localStorage['zepto']);
		eval(localStorage['wxcommon']);
		getparams();
	}
})();


function getparams(){
	GlobalConfig.geturl = g_cgi_getmsgrecord+"?";
	GlobalConfig.getunreadurl = g_cgi_getunreadmsg+"?";
	GlobalConfig.pushurl = g_cgi_sendmsg+"?";
	GlobalConfig.grabcustomer = g_cgi_robcase+"?";
	GlobalConfig.f = decodeURIComponent(LeogsgetParams({pNames:["f"],url:_localhref})||"");
	GlobalConfig.title = decodeURIComponent(LeogsgetParams({pNames:["n"],url:_localhref})||"");
	GlobalConfig.cid = LeogsgetParams({pNames:["cid"],url:_localhref})||"";
	GlobalConfig.openid = LeogsgetParams({pNames:["openid"],url:_localhref})||"";
	GlobalConfig.w = LeogsgetParams({pNames:["userid"],url:_localhref})||"";
	
	g_exportkey =LeogsgetParams({pNames:["exportkey"],url:_localhref})||"";
	
	if(g_exportkey == "" || g_exportkey == undefined)
	{
		g_bossidval=getCookie("bizid")||"";
		g_workeridval=getCookie("workerid")||"";
		g_tokenval=getCookie("passkeytoken")||"";
		g_account=getCookie("workeraccount")||"";
		
		enter(0);
	}
	else
	{
		var _retCoder=returnCode({url:g_cgi_GetTokenAndWorkerIndex,frequence:10});
		
		$.ajax({
			type: 'GET',
			url: g_cgi_GetTokenAndWorkerIndex + "?passkey=" + g_exportkey + "&t=" +new Date().getTime(),
			dataType: "jsonp",
			success: function(d){
				
				g_bossidval = d.bizid;
				g_workeridval = d.workerid;
				g_tokenval = d.passkeytoken;
				g_account =d.workeraccount;
				_retCoder.report(true,d.ret);
				
				enter(d.ret);
			},
			error: function(xhr, type){
				DialogBox.tips('网络请求错误，请稍后重试!');
				_retCoder.report(false,443);
			}
		});
	}
}


document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
    WeixinJSBridge.invoke('hideToolbar');
	WeixinJSBridge.invoke('hideOptionMenu');
	window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
}, false)
/******************************
 多客服卖家微信消息

 20121206 liuyang 创建
/******************************
　初始化配置
*******************************/

function enter(ret){
	if(ret==0){
		//有绑定关系
		GlobalConfig.uin = g_bossidval;
		GlobalConfig.test = "&passkeytoken="+g_tokenval;
		init();
	}
	else if(ret==9){
	//无绑定关系
		crm_gotopage(g_url_bind, "jump=1&exportkey="+g_exportkey);
	}
	else{
	//出错
		crm_errortip(ret);
	}
}

function init(){
	initData();
	delunReadMess();
	bindEvent();
};
function initData(){
    document.title=Leogsxss(GlobalConfig.title,"html");
	if(GlobalConfig.f==1){		
		$("#gobackname").html("通话记录");
	}
	else{
		$("#gobackname").html("联系人");	
	}

	 _retCoderunread=returnCode({url:g_cgi_initializejsapi,frequence:10});
     $.ajax({
            type: 'GET',
            url: g_cgi_initializejsapi+"?t="+new Date().getTime(),
            dataType: 'jsonp',
            success: function(d){
				if(d.ret == 0)
				{
					wx.config({
     					debug: false,
      					appId: d.appId,
      					timestamp: d.timestamp,
      					nonceStr: d.nonceStr,
      					signature: d.signature,
      					jsApiList: ['startRecord','stopRecord','onRecordEnd','uploadVoice','chooseImage','uploadImage','downloadImage','previewImage']
  					});
					
					wx.ready(function () {
  						$("#imagebtn").show();	
						$("#voicebtn").show();	
					});
					
					wx.error(function (res) {
						$("#imagebtn").hide();	
						$("#voicebtn").hide();
  						DialogBox.tips('微信注册失败!');	   
					});
				}
            },
            error: function(xhr, type){ 
				DialogBox.tips('获取微信注册信息失败!');	   
            }
    });	
}
/*绑定事件*/
function bindEvent(){		
	$("#newswarn_btn").click(function(e){	
		crm_gotopage(g_url_recentlist, "");
	});
	$("#chat_chatmsglist").click(function(e){
			$("#emojicon").hide();		
	});
	/*发送按钮*/
	$("#sendmBtn").click(function(e){
		if($('#sendmBtn').html() == "发送")
		{
			pushMess();
		}
		else
		{
			$("#textInput").show();
			$("#recordbtn").hide();
			$('#sendmBtn').html("发送");
		}
	});
	/*关闭显示更多（转接）按钮*/  
	$("#cancelmorebtn").click(function(e){
			$("#moreCon").hide();
			$("#floatBgCon").hide();
			
	});
	/*开启转接*/	
	$("#switchbtn").click(function(e){
		crm_gotopage(g_url_workerlist, "visitid="+GlobalConfig.w);
	});
	/*显示更多（转接）按钮*/  
	$("#iconmorebtn").click(function(e){
			$("#moreCon").show();
			$("#floatBgCon").show();
	});
    /*显示表情按钮*/    
	$("#iconemojibtn").click(function(e){
		if($("#emojicon").css("display")){
			$("#emojicon").show();
		}
		else{		
			$("#emojicon").hide();
		}
	});
	/*表情相关事件*/
	$("#emojicon img").click(function(e){
		var t = $getTarget(e,this,"img");
		if(t){
			//添加表情到输入框
			$("#textInput").val($("#textInput").val()+EditorHelper.encodeEmotion(t.outerHTML));
		}
	});

	$("#textInput").focus(function(e){
		//document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
			window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
    });
	$("#textInput").blur(function(e){      
			window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
    });
	/*开启语音*/	
	$("#voicebtn").click(function(e){
		$("#moreCon").hide();
		$("#floatBgCon").hide();
		$("#textInput").hide();
		$("#recordbtn").show();
		$('#sendmBtn').html("返回");
		GlobalConfig.isrecording=0;
	});
	
	function EndVoice(r)
	{
		GlobalConfig.isrecording=0;
		$('#recordbtn').toggleClass("voice-sending_on", false);
		$('#recordbtn').html("按住录音");
		$('#chattmphtml').remove();
		$("#tipvoice").hide();
		wx.uploadVoice({
      		localId: r.localId,
      		success: function (res) {pushMess(7, res.serverId);}
    	});
	}
	
	document.getElementById("recordbtn").ontouchstart = function(e) { 
		if(GlobalConfig.isrecording==0)
		{
			wx.startRecord({
				cancel: function () {
				},
				success:function(){
					$('#recordbtn').toggleClass("voice-sending_on", true);
					$('#recordbtn').html("松开发送语音");
					$("#tipvoice").show();
					GlobalConfig.isrecording=1;
					GlobalConfig.chathtml=GlobalConfig.chattmphtml.replace(/{#ctime#}/g,changeTimeFormat(new Date())).replace(/{#nick#}/g,"");
					$("#chat_chatmsglist").append(GlobalConfig.chathtml);
					document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
					window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
	
					wx.onVoiceRecordEnd({//语音最长一分钟
						complete: function (res) {
							EndVoice(res);	
						}
					});
				},
				fail: function (res) {
					alert(JSON.stringify(res));
				}
			});	
		}
		e.preventDefault(); 
    };
	
	document.getElementById("recordbtn").ontouchend = function(e) { 
		if(GlobalConfig.isrecording!=0)
		{
			wx.stopRecord({
      			success: function (res) {
					EndVoice(res);	
      			},
      			fail: function (res) {
       				alert(JSON.stringify(res));
      			}
    		});
		}
    };
	

				
	/*开启图片*/	
	$("#imagebtn").click(function(e){
		$("#moreCon").hide();
		$("#floatBgCon").hide();
		wx.chooseImage({
      		success: function (res) {
				alert("您总共选择了" + res.localIds.length + "张图片");
        		if (res.localIds.length == 0) {
      				return;
    			}
    			var i = 0, length = res.localIds.length;
    			function upload() {
      				wx.uploadImage({
        				localId: res.localIds[i],
        				success: function (res) {
          					i++;
          					pushMess(3, res.serverId);
							alert('已上传：' + i + '/' + length);
          					if (i < length) {upload();}
       			 		},
        				fail: function (res) {
          					alert(JSON.stringify(res));
        				}
      				});
    			}
    			upload();
     	 	}
    	});	
	});
}

/******************************
　功能实现区
*******************************/
/*删除未接入会话*/
function delunReadMess(){
		 _retCoderdel=returnCode({url:g_cgi_delunreadmsg,frequence:10});
        $.ajax({
            type: 'GET',
            url: g_cgi_delunreadmsg+"?"+GlobalConfig.test+"&bossid="+GlobalConfig.uin+"&workerid="+g_workeridval+"&customerid="+GlobalConfig.w+"&t="+new Date().getTime(),
            dataType: 'jsonp',
            success: function(d){
				delunreadmsgfun(d);
            },
            error: function(xhr, type){
                DialogBox.tips('网络请求错误,请返回重试');
				_retCoderdel.report(false,443);
            }
        });	
}

function delunreadmsgfun(d){
	if(d.ret==0){
		getMess(0);
	}
	else if(d.ret==3){//用户被其他工号接入
		$("#caseexist").hide();
		$("#casenotexist").show();
		getMess(0);
	}
	else{
		crm_errortip(d.ret,d.errmsg);
	}
	_retCoderdel.report(true,d.ret);
}

/*抢接会话*/
var  grabCustomer=function(rt){
		 _retCodergrab=returnCode({url:GlobalConfig.grabcustomer,frequence:10});
        $.ajax({
            type: 'GET',
            url: GlobalConfig.grabcustomer+GlobalConfig.test+"&robtype="+rt+"&bossid="+GlobalConfig.uin+"&workerid="+g_workeridval+"&customerid="+GlobalConfig.w+"&t="+new Date().getTime(),
            dataType: 'jsonp',
            success: function(d){
				grabCFun(d);
            },
            error: function(xhr, type){
                DialogBox.tips('网络请求错误,请返回重试');
				_retCodergrab.report(false,443);
            }
        });	
		$('#tipsCon').hide();
}

var grabCFun=function(d){
	if(d.ret==0){
		//抢接成功		
		$("#caseexist").show();
		$("#casenotexist").hide();
		document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
	}
    else if(d.ret==20){
		$("#tipsmsg").html(Leogsxss(d.errmsg,"html"));
		$("#tipsCon").show();
    }
	else{
        crm_errortip(d.ret,d.errmsg);
	}
	_retCodergrab.report(true,d.ret);
}

/*获取消息*/
var getMess=function(ty){		
	var date = new Date();
	if(ty==0){
		 _retCodergeturl=returnCode({url:GlobalConfig.geturl,frequence:10});
        $.ajax({
            type: 'GET',
            url: GlobalConfig.geturl+"bossid="+GlobalConfig.uin+"&workerid="+g_workeridval+"&msgtype="+ty+"&customerid="+GlobalConfig.w+"&pgid="+GlobalConfig.pid+"&pgsize=10&begintime=0&msgtype=0&endtime="+parseInt(parseInt(date.getTime())/1000)+"&t="+new Date().getTime()+GlobalConfig.test,
            dataType: 'jsonp',
            success: function(d){
				showMessList(d);	
				$('.ui-refresh').refresh({
					load: function (dir, type) {			
							var me = this;			   
							var date = new Date();
							GlobalConfig.pid++;
									_retCodergeturl=returnCode({url:GlobalConfig.geturl,frequence:10});
							$.ajax({
								type: 'GET',
								url: GlobalConfig.geturl+"bossid="+GlobalConfig.uin+"&workerid="+g_workeridval+"&msgtype=0&customerid="+GlobalConfig.w+"&pgid="+GlobalConfig.pid+"&pgsize=10&begintime=0&msgtype=0&endtime="+parseInt(parseInt(date.getTime())/1000)+"&t="+new Date().getTime()+GlobalConfig.test,
								dataType: 'jsonp',
								success: function(d){
											showMessList(d);	
											me.afterDataLoading(dir);    //数据加载完成后改变状态,dir可传可不传，不传则为当前加载的refresh按钮
														_retCodergeturl.report(true,d.ret);
								},
								error: function(xhr, type){
									DialogBox.tips('网络请求错误,请返回重试');
												_retCodergeturl.report(false,443);
								}
							});	
						GlobalConfig.unread=1;
					}
			});
	document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
	window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);		
						_retCodergeturl.report(true,d.ret);
            },
            error: function(xhr, type){
                DialogBox.tips('网络请求错误,请返回重试');			
				_retCodergeturl.report(false,443);
            }
        });	
	GlobalConfig.unread=1;
	}
	else if(ty=1){
		 _retCoderunread=returnCode({url:GlobalConfig.getunreadurl,frequence:10});
        $.ajax({
            type: 'GET',
            url: GlobalConfig.getunreadurl+"workerid="+g_workeridval+"&bossid="+GlobalConfig.uin+"&customerid="+GlobalConfig.w+"&t="+new Date().getTime()+GlobalConfig.test,
            dataType: 'jsonp',
            success: function(d){
				showMessList(d);
				_retCoderunread.report(true,d.ret);
            },
            error: function(xhr, type){
                DialogBox.tips('网络请求错误,请返回重试');					
				_retCoderunread.report(false,443);
            }
        });			
	GlobalConfig.unread=0;
	}
}
/*发送消息*/
var pushMess=function(type, mediaID){
	var content ="";
	if(type == 7)//语音
	{
		content+='{"ElementType":' + type + ',"Attr":[{"AttrType":1,"Text":"'+mediaID+'"}]}';
	}
	else if(type == 3)//图片
	{
		content+='{"ElementType":' + type + ',"Attr":[{"AttrType":21,"Text":"'+mediaID+'"}]}';
	}
	else
	{
		type = 1;
		var sendemotionCon =EditorHelper.removeContentAndEmotion($("#textInput").val());
		var reg=/(\[[^\s]{1,3}\])/g;
		for(var i=0;i<sendemotionCon.length;i++){
			var con = sendemotionCon[i];			
				if(content!=""){
					content+=",";
				}
				if(EditorHelper.existContentAndEmotion(con)=="true"){
					content+='{"ElementType":2,"Attr":[{"AttrType":1,"Text":"'+EditorHelper.decodeSendEmotion(con)+'"}]}';
				}
				else{
					content+='{"ElementType":1,"Attr":[{"AttrType":1,"Text":"'+con+'"}]}';
				}
		}
	}
	
var aj_data='bossid='+GlobalConfig.uin+'&workerid='+g_workeridval+'&customerid='+GlobalConfig.w+'&mshtype=0&content={"msg":['+content+']}'+GlobalConfig.test+"&t="+new Date().getTime();
		 _retCoderpushurl=returnCode({url:GlobalConfig.pushurl,frequence:10});
        $.ajax({
            type: 'GET',
            url: GlobalConfig.pushurl+aj_data,
            dataType: 'jsonp',
            success: function(d){
				d.type = type;
				pushedMess(d);
				_retCoderpushurl.report(true,d.ret);
            },
            error: function(xhr, type){
                DialogBox.tips('网络请求错误,请返回重试');			
				_retCoderpushurl.report(false,443);
            }
        });		
	
}
/*发送完消息显示列表*/
var pushedMess=function(d){
	if(d.ret==0){
		GlobalConfig.mid = d.mid;
	//更新发布中的列表
		var myDate=new Date()
		if(GlobalConfig.lasttime==""||(GlobalConfig.lasttime<changeTimeFormat(myDate-15*60*1000))){
			GlobalConfig.chathtml=GlobalConfig.chattime.replace(/{#msgtime#}/g,changeTimeFormat(myDate));
			GlobalConfig.lasttime=changeTimeFormat(myDate);
		}
		var content = "";
		if(d.type == 1)
		{
			content = '<div class="mod-chat__message">'+EditorHelper.decodeEmotion($("#textInput").val())+'</div>';
		}
		else if(d.type == 7)
		{
			content = '<span class="icoVoice play" un="voiceStatus"  onclick="play(\''+g_cgi_downloadmedia4wechat+'?bossuin='+GlobalConfig.uin+'&vt=1&mediaid='+d.convertedMediaId+'&timestamp='+d.timestamp+'&appid=wxfe20f87cdf852ee3\',this)"></span>';
		}
		else if(d.type == 3)
		{
			var srcUrl=g_cgi_downloadmedia4wechat+'?mediaid='+d.convertedMediaId+'&timestamp='+d.timestamp+'&bossuin='+GlobalConfig.uin;
			content = '<img class="mod-chat__message-img" src="'+srcUrl +'" alt="" onclick="popImage(this);"  onerror="setTimeout(\"this.src=\"' + srcUrl + '\"\", 3000)"/>';
		}
		
		GlobalConfig.chathtml=GlobalConfig.chatmehtml.replace(/{#ctime#}/g,changeTimeFormat(myDate)).replace(/{#nick#}/g,"").replace(/{#cloudTI#}/g,"cloudText").replace(/{#ccon#}/g, content).replace(/{#id#}/g,"sending");
		
  		$("#chat_chatmsglist").append(GlobalConfig.chathtml);
		$("#textInput").val("");
	}
	else if(d.ret==3){	
		 DialogBox.tips("发送失败，原因："+kfErrorCode[d.ret],function(){                     			
					$("#caseexist").hide();
					$("#casenotexist").show();
				});
	}
	else{
        crm_errortip(d.ret,d.errmsg);
	}
    $("#emojicon").hide();
	//document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
	window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
}
/*显示消息*/
var showMessList=function(d){
	if(d.ret==0){
        if(d.othermsg&&(d.othermsg!=0)){//这个时候有其他用户给该商户发消息，提示小黄条
            $("#newswarn_btn").show();
				document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
        }
        var data = d.data;
		if(data.length==0){
			return;
		}
        formatMess(data);
        if(d.subscribe&&(d.subscribe==1)){//取消关注了，不会再拉取未读消息
            $("#input_con").hide();
        }
        else{
            /*开始计时*/
            if(GlobalConfig.his){
                rollSend();
                GlobalConfig.his=0;
            }
        }
	}
}

/*装载消息*/
var loadMess=function(m){	
var strMsg="";
		for(var j=0;j<m.length;j++){
			var msg=m[j];
				if(!msg){
					continue;
				}
			Attr=msg.Attr[0];
			switch(msg.ElementType){
				case "1":{//文本
                    for(k = 0; k < msg['Attr'].length; ++k){
                        if(msg['Attr'][k]['AttrType'] == '1'){
						   strMsg+=msg['Attr'][k].Text;
                            break;
                        }
                    }
					break;
					}
				case "2":{//表情
					strMsg += '<img src="http://o2o.gtimg.com/dkf/img/wx/' + Attr.Text + '.png">';
					break;
					}
				case "3":{	//图片	
                    var imgUrl = '';
                    attrSize = msg['Attr'].length;
                    for(k = 0; k < attrSize; ++k){
                        if(msg['Attr'][k]['AttrType'] == '22'){  //微信的图片的url
                            imgUrl = msg['Attr'][k]['Text'];
       							 strMsg = strMsg+'<img class="mod-chat__message-img" src="'+imgUrl+'" alt="" onclick="popImage(this);" />';
                            break;
                        }
                    }
                    var mediaID = '';
                    if(imgUrl == ''){
                        for(k = 0; k < attrSize; ++k){
                            if(msg['Attr'][k]['AttrType'] == '21'){ //微信的图片的mediaid
                                mediaID = msg['Attr'][k]['Text'];
       							 strMsg = strMsg+'<img class="mod-chat__message-img" src="'+g_cgi_downloadmedia4wechat+'?mediaid='+mediaID+'&timestamp='+d.time+'&bossuin='+GlobalConfig.uin+'" alt="" onclick="popImage(this);" />';
                                break;
                            }
                        }
                    }	
                                break;
				}
					case "7":{//语音
						var mediaID = '';
						attrSize = msg.Attr.length;      
						if(mediaID == ''){
							for(k = 0; k < attrSize; ++k){
								if(msg.Attr[k]['AttrType'] == '1'){
									mediaID = msg.Attr[k]['Text'];
									break;
								}
							}
						}

       				strMsg = strMsg+'<span class="icoVoice play" un="voiceStatus"  onclick="play(\''+g_cgi_downloadmedia4wechat+'?bossuin='+GlobalConfig.uin+'&vt=1&mediaid='+mediaID+'&timestamp='+d.time+'&appid=wxfe20f87cdf852ee3\',this)"></span>';
					break;	
					}
                case "8":{//发起人信息
                    break;
                }
				case "12":{//地理位置
				 var addr='';
                            attrSize = msg['Attr'].length;
                            for(k = 0; k < attrSize; ++k){
                                if(msg['Attr'][k]['AttrType'] == '15'){
                                    addr = Leogsxss(msg['Attr'][k]['Text'], 'html');
                                    continue;
                                }
                            }
							strMsg +='<div class="mod-chat__message_map" ><img class="mod-chat__message-img" src="http://o2o.gtimg.com/dkf/img/wx/gps.png" alt=""><div class="mod-chat__message-mask"><div class="mod-chat__message-mask-text">'+addr+'</div></div></div>';
					break;	
				}
                case "14":{//发起人信息
                    break;
                }
                case "18":{//发起人信息
                    break;
                }
                default:{
					strMsg="暂不支持多媒体";
					break;	
					}
			}			
		}
		return strMsg;

}
/*格式化消息*/
var formatMess=function(o){
	var l = o.length;
	if(l!=0){
	GlobalConfig.chathtml="";
	var str="";
		for(var i=l;i>=0;i--){			
			d=o[i];
			if(d){
                if(d.msg.length==0){
                    continue;
                }
				str=loadMess(d.msg);
					if(d.dir=="1"){//自己的消息
								if(GlobalConfig.lasttime==""||(GlobalConfig.lasttime<changeTimeFormat(d.time*1000-15*60*1000))){
									GlobalConfig.chathtml+=GlobalConfig.chattime.replace(/{#msgtime#}/g,changeTimeFormat(d.time*1000));
									GlobalConfig.lasttime=changeTimeFormat(d.time*1000);
								}
							    GlobalConfig.chathtml+=GlobalConfig.chatmehtml.replace(/{#ccon#}/g,str).replace(/{#nick#}/g, d.workernick);
					}
					else if(d.dir=="2"){//别人的消息
								if(GlobalConfig.lasttime==""||GlobalConfig.lasttime<changeTimeFormat(d.time*1000-15*60*1000)){
								GlobalConfig.chathtml+=GlobalConfig.chattime.replace(/{#msgtime#}/g,changeTimeFormat(d.time*1000));
									GlobalConfig.lasttime=changeTimeFormat(d.time*1000);
								}
								GlobalConfig.chathtml+=GlobalConfig.chatyouhtml.replace(/{#ccon#}/g,str);
					}
			}
		}
				if(!GlobalConfig.unread){
					//拉取未读消息
  					$("#chat_chatmsglist").append(GlobalConfig.chathtml);
					if((document.getElementById('ui-refresh').scrollHeight-(document.getElementById('ui-refresh').clientHeight +document.getElementById('ui-refresh').scrollTop))<120){
						document.getElementById('ui-refresh').scrollTop = document.getElementById('ui-refresh').scrollHeight;
						window.scrollTo(0,document.getElementById('ui-refresh').scrollHeight+80);
						}
				}
				else{
					//拉取已读消息
  					$("#chat_chatmsglist").prepend(GlobalConfig.chathtml);
				}
		}
}

/*放大接收图片*/
var popImage = function(s) {
    if(s.src){
        var arr= [];
        arr.push(s.src);
        wx.previewImage({
        	current:s.src,
        	urls:arr,
			fail: function (res) {
          		alert(JSON.stringify(res));
        	}
		});
    }
}
/*轮询消息*/
var rollSend=function(){
	setInterval(function(){
		getMess(1);//拉取未读消息
	},10000);
}

/*表情*/

var EditorHelper = (function() {
    return {
        emotionTitleList : ['惊讶', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙',
                        '微笑', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '愉快', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑',
                        '悠闲', '奋斗', '咒骂', '疑问', '嘘', '晕', '疯了', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', 
                        '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', 
                        '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', '凋谢', '嘴唇', '爱心', '心碎', '蛋糕', '闪电', 
                        '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', 
                        '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', 
                        '投降', '激动', '乱舞', '献吻', '左太极', '右太极'],
        encodeEmotion : function(content) {
            content = EditorHelper.removeTextMsgTag(content);
            return content.replace(/<(img|IMG)\s+src="http:\/\/o2o.gtimg.com\/dkf\/img\/wx\/(\d+)@2x.(png)"[\s\S]*?>/g, function($0, $1, $2) {
                return $0.replace($0, "["+EditorHelper.emotionTitleList[$2]+"]");
            });
        },
        decodeEmotion : function(content) {
            content = EditorHelper.removeTextMsgTag(content);
            return content.replace(/(\[[^\s]{1,3}\])/g, function($0, $1) {
                return $1.replace(/\[([^\s]{1,3})\]/g, function($0, $1) {
                    return EditorHelper.getImgByTitle($1);
                });
            });
        },
        removeContentAndEmotion : function(content) {
            content = EditorHelper.removeTextMsgTag(content);
			result = content.match(/(\[.+?\]|[^[\]]+)/img);
           return result;
        },
		/*拆解发送内容，区分文字和表情*/		
        decodeSendEmotion : function(content) {
            content = EditorHelper.removeTextMsgTag(content);
            return content.replace(/(\[[^\s]{1,3}\])/g, function($0, $1) {
                return $1.replace(/\[([^\s]{1,3})\]/g, function($0, $1) {
                    return EditorHelper.getiByTitle($1);
                });
            });
        },
		/*是否为表情*/
        existContentAndEmotion : function(content) {
            content = EditorHelper.removeTextMsgTag(content);
            return content.replace(/(\[[^\s]{1,3}\])/g, function($0, $1) {
                return $1.replace(/\[([^\s]{1,3})\]/g, function($0, $1) {
                    return true;
                });
            });
        },
        getImgByTitle : function(title) {
            for(var i=0,len=EditorHelper.emotionTitleList.length; i<len; i++) {
                if(EditorHelper.emotionTitleList[i] == title) {
                    var img = '<img src="http://o2o.gtimg.com/dkf/img/wx/'+i+'.png"/>';
                    return img;
                }
            }
            return "";
        },
        getiByTitle : function(title) {
            for(var i=0,len=EditorHelper.emotionTitleList.length; i<len; i++) {
                if(EditorHelper.emotionTitleList[i]== title) {
                    return i;
                }
            }
            return "";
        },
        removeTextMsgTag : function(content) {
            content = content.replace(/<(p|P)>/g, '').replace(/<\/(p|P)>/g, '').replace(/<(br|BR)\s*\/?>/g, '').replace(/\n/g, '');
            return content;
        }
    };
})();

var audio = document.getElementById('audio1');
audio.addEventListener('ended', function(evt) {
	$(currdom).removeClass("icoVoicePlaying");
});
var currdom=null;

var play=function(url,dom){
		if($(dom).hasClass("icoVoicePlaying")){
		audio.pause();
		audio.currentTime="";
		$(dom).removeClass("icoVoicePlaying");
	}
	else{
		if(currdom){
			$(currdom).removeClass("icoVoicePlaying");
		}
		currdom=dom;
		localStorage['audiols']=url;
		audio.src =localStorage['audiols'];
		audio.play();
		$(dom).addClass("icoVoicePlaying");
	}
}



</script></body></html>